package com.joker.cart.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.joker.cart.constants.RedisConstants;
import com.joker.cart.domain.CartSkuVO;
import com.joker.cart.domain.CartVO;
import com.joker.cart.domain.PmsCart;
import com.joker.cart.domain.PmsCartSku;
import com.joker.cart.service.IPmsCartService;
import com.joker.cart.service.IPmsCartSkuService;
import com.joker.cart.utils.CartUtils;
import com.joker.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lemon
 * @date 2024/12/29 19:26
 **/
@Component
public class Redis2MySQL {

    @Autowired
    private IPmsCartService pmsCartService;

    @Autowired
    private IPmsCartSkuService pmsCartSkuService;

    @Autowired
    private RedisService redisService;

    @Scheduled(cron = "* * 1 * * *")
    public void CartSyn(){
        Collection<String> keys = redisService.keys(RedisConstants.USER_CART + "*");
        for (String key : keys) {
            Map<String, Object> cacheMap = redisService.getCacheMap(key);
            List<CartSkuVO> list = JSONObject.parseObject(JSONObject.toJSONString(cacheMap.values()),
                    new TypeReference<List<CartSkuVO>>() {});
            List<CartVO> cartVOList = CartUtils.cartSkuVOS2CartVOS(list);

            for (CartVO cartVO : cartVOList) {
                Long merchantId = cartVO.getMerchantId();
                Long userId = Long.valueOf(key.split(":")[1]);
                PmsCart pmsCart = pmsCartService.selectByMerchantIdAndUser(merchantId,userId);
                if (pmsCart == null){
                    pmsCart = new PmsCart();
                    pmsCart.setUserId(userId);
                    pmsCart.setMerchantName(cartVO.getMerchantName());
                    pmsCart.setMerchantId(merchantId);
                    pmsCartService.insertPmsCart(pmsCart);
                }
                PmsCart finalPmsCart = pmsCart;
                pmsCartSkuService.deleteByCartId(finalPmsCart.getCartId());


                List<PmsCartSku> pmsCartSkuList= cartVO.getList().stream().map(cartSkuVO -> {
                    PmsCartSku pmsCartSku = new PmsCartSku();
                    pmsCartSku.setCartId(finalPmsCart.getCartId());
                    pmsCartSku.setCount(cartSkuVO.getCount());
                    pmsCartSku.setSkuId(cartSkuVO.getSkuId());
                    pmsCartSku.setStatus(cartSkuVO.getChecked());
                    return pmsCartSku;
                }).collect(Collectors.toList());

                pmsCartSkuService.addBatch(pmsCartSkuList);
            }
        }
    }
}
